package com.Controller;

import com.Service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin/order")
public class AdminOrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/list")
    public String list(Model model) {
        model.addAttribute("orderList", orderService.findAll());
        return "admin/order/list";
    }
    @GetMapping("/changeStatusPage")
    public String changeStatusPage(@RequestParam Long id, Model model) {
        System.out.println(orderService.findById(id));
        model.addAttribute("order", orderService.findById(id));
        return "admin/order/edit";
    }

    @PostMapping("/changeStatus")
    public String changeStatus(@RequestParam Long orderId, @RequestParam String status, RedirectAttributes ra) {
        try {
            orderService.updateStatus(orderId, status);
            ra.addFlashAttribute("successMessage", "状态更新成功");
        } catch (Exception ex) {
            ra.addFlashAttribute("errorMessage", "状态更新失败：" + ex.getMessage());
        }
        return "redirect:/admin/order/list";
    }

    @GetMapping("/delete")
    public String delete(@RequestParam Long id, RedirectAttributes ra) {
        try {
            orderService.delete(id);
            ra.addFlashAttribute("successMessage", "删除订单成功");
        } catch (DataIntegrityViolationException ex) {
            ra.addFlashAttribute("errorMessage", "删除失败：请先删除相关订单项");
        }
        return "redirect:/admin/order/list";
    }




}
